package com.tbfs.util;

/*
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 



import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;

import org.apache.commons.codec.binary.Hex;

/**
 * Operations to simplifiy common {@link java.security.MessageDigest} tasks.  This
 * class is thread safe.
 *
 * @author Apache Software Foundation
 */
public class DigestUtils {
	private static  byte[] linkoolkey ={-104,-94,-2,-56,-23,104,59,79};
    /**
     * Returns a MessageDigest for the given <code>algorithm</code>.
     *
     * @param algorithm The MessageDigest algorithm name.
     * @return An MD5 digest instance.
     * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
     */
    static MessageDigest getDigest(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * Returns an MD5 MessageDigest.
     *
     * @return An MD5 digest instance.
     * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
     */
    private static MessageDigest getMd5Digest() {
        return getDigest("MD5");
    }

    /**
     * Returns an SHA digest.
     *
     * @return An SHA digest instance.
     * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
     */
    private static MessageDigest getShaDigest() {
        return getDigest("SHA");
    }
    
    
    /**
     * Calculates the MD5 digest and returns the value as a 16 element 
     * <code>byte[]</code>.
     *
     * @param data Data to digest
     * @return MD5 digest
     */
    public static byte[] md5(byte[] data) {
        return getMd5Digest().digest(data);
    }

    /**
     * Calculates the MD5 digest and returns the value as a 16 element 
     * <code>byte[]</code>.
     *
     * @param data Data to digest
     * @return MD5 digest
     */
    public static byte[] md5(String data) {
        return md5(data.getBytes());
    }

    /**
     * Calculates the MD5 digest and returns the value as a 32 character 
     * hex string.
     *
     * @param data Data to digest
     * @return MD5 digest as a hex string
     */
    public static String md5Hex(byte[] data) {
        return new String(Hex.encodeHex(md5(data))).toUpperCase();
    }

    /**
     * Calculates the MD5 digest and returns the value as a 32 character 
     * hex string.
     *
     * @param data Data to digest
     * @return MD5 digest as a hex string
     */
    public static String md5Hex(String data) {
        return new String(Hex.encodeHex(md5(data))).toUpperCase();
    }

    /**
     * Calculates the SHA digest and returns the value as a 
     * <code>byte[]</code>.
     *
     * @param data Data to digest
     * @return SHA digest
     */
    public static byte[] sha(byte[] data) {
        return getShaDigest().digest(data);
    }

    /**
     * Calculates the SHA digest and returns the value as a 
     * <code>byte[]</code>.
     *
     * @param data Data to digest
     * @return SHA digest
     */
    public static byte[] sha(String data) {
        return sha(data.getBytes());
    }

    /**
     * Calculates the SHA digest and returns the value as a hex string.
     *
     * @param data Data to digest
     * @return SHA digest as a hex string
     */
    public static String shaHex(byte[] data) {
        return new String(Hex.encodeHex(sha(data)));
    }

    /**
     * Calculates the SHA digest and returns the value as a hex string.
     *
     * @param data Data to digest
     * @return SHA digest as a hex string
     */
    public static String shaHex(String data) {
        return new String(Hex.encodeHex(sha(data)));
    }
    
   
     /**
      *将指定的数据根据提供的密钥进行加密
      *@paraminput需要加密的数据
      *@paramkey密钥
      *@returnbyte[]加密后的数据
      *@throwsException
      */
    private static byte[] encryptData (byte []input ,byte []key )throws Exception 
      {
          SecretKey deskey =new javax.crypto.spec.SecretKeySpec (key ,"DES"  );
          Cipher c1 =Cipher.getInstance ("DES"  );
          c1.init (Cipher.ENCRYPT_MODE ,deskey );
          byte []cipherByte =c1.doFinal (input );
          return cipherByte ;
      }
      /**
      *将给定的已加密的数据通过指定的密钥进行解密
      *@paraminput待解密的数据
      *@paramkey密钥
      *@returnbyte[]解密后的数据
      *@throwsException
      */
      private static byte[] decryptData (byte []input ,byte []key )throws Exception 
      {
          SecretKey deskey =new javax.crypto.spec.SecretKeySpec (key ,"DES"  );
          Cipher c1 =Cipher.getInstance ("DES"  );
          c1.init (Cipher.DECRYPT_MODE ,deskey );
          byte[] clearByte =c1.doFinal (input );
          return clearByte ;
      }
     

      /**
       *将指定的数进行加密
       *@str需要加密的数据
	
       */
    public static String encoder(String str)
    {
    	if(str==null || str.length()==0) return "";
    	try{
           return new String(Hex.encodeHex(encryptData (str.getBytes() ,linkoolkey )));
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	return "";
    }
    /**
     *将指定的数进行解密
     *@str需要加密的数据
	
     */
    public static String decoder(String str)
    {
    	if(str==null || str.length()==0) return "";
    	try{
    		return new String(decryptData (Hex.decodeHex(str.toCharArray()) ,linkoolkey ));
    	}catch(Exception e)
    	{}
    	return "";
    }
    
    public static  String computeMD5(String inputStr) {

    		return md5Hex(inputStr);
//        MessageDigest md5=null;
//        try {
//            //创建MD5函数对象
//            md5 = MessageDigest.getInstance("MD5");
//        } catch (Exception e) {
//            System.out.println(e.toString());
//            e.printStackTrace();
//            return "";
//        }
//        char[] charArray = inputStr.toCharArray(); //将字符串转换为字符数组
//        byte[] byteArray = new byte[charArray.length]; //创建字节数组
//
//        for (int i = 0; i < charArray.length; i++)
//        //将字符转换为字节
//         byteArray[i] = (byte) charArray[i];
//
//        //将得到的字节数组进行MD5运算
//         byte[] md5Bytes = md5.digest(byteArray);
//
//        StringBuffer reMD5Str= new StringBuffer();
//
//        for (int i = 0; i < md5Bytes.length; i++) {
//            int val = ((int) md5Bytes[i]) & 0xff;
//            if (val < 16)
//            	reMD5Str.append("0");
//           // reMD5Str.append(Integer.toBinaryString(val));
//            reMD5Str.append(Integer.toHexString(val));
//        }
//
//       //返回信息摘要结果字符串
//        return reMD5Str.toString();
    }
    
   /* public static String getBASE64(byte[] s) {
    	if (s == null) return null;
    	return (new sun.misc.BASE64Encoder()).encode( s );
    	} 
    public static String getDecodeBASE64(String s) {
    	if (s == null) return null;
    	try{
    		return new String(Hex.encodeHex((new sun.misc.BASE64Decoder()).decodeBuffer(s))).toUpperCase();
    	}catch(Exception e){
    		return null;
    	}
    	} 
    public static String getBASE64MD5(String s) {
    	if (s == null) return null;
    	return (new sun.misc.BASE64Encoder()).encode(md5(s));
    	} */
    public static void main(String[] args) throws Exception
    {
    	System.out.println(md5Hex("a").toUpperCase());
    	//System.out.println(md5Hex("ab").toUpperCase());
    	//System.out.println(md5Hex("72-1319769697-easySNS#private_key").toUpperCase());
    	//System.out.println( )
    //	System.out.println(md5Hex("111111").toUpperCase().substring(8,24));
    	String s="ldb1978";
    	String md5= md5Hex(s);
//    	String md564= getBASE64MD5(s);
//    	String md52= getDecodeBASE64(md564);
    	System.out.println(md5);
//    	System.out.println(md564);
//    	System.out.println(md52);
    	System.out.println(DigestUtils.computeMD5(s));
//    	String es =new String(Base64.encode(s.getBytes()));
//    	System.out.println(es);
//    	System.out.println(new String(Base64.decode(es.getBytes())));
    //	System.out.println( getBASE64(md5(s)));
    //	System.out.println( computeMD5(s));
//    	sun.misc.BASE64Encoder base64Encoder = new sun.misc.BASE64Encoder();
    	
    	
    }
}

